Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed optional typing on non-serializable types #2939

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from

Conversation

AlexejPenner
Copy link
Contributor

Describe changes

This code:

from typing import Optional

from zenml import step, pipeline
from sklearn.neighbors import NearestNeighbors
import numpy as np


@step
def one():
    X = np.array([[1, 1], [2, 2]])
    return NearestNeighbors().fit(X)


@step
def two(a: Optional[int] = None, nn: Optional[NearestNeighbors] = None):
    pass


@pipeline()
def simple_pipeline():
    nn = one()
    two(nn=None, a=None)


simple_pipeline()

Was failing with the following error message:

│    404 │   def _unknown_type_schema(self, obj: Any) -> CoreSchema:                               │
│ ❱  405 │   │   raise PydanticSchemaGenerationError(                                              │
│    406 │   │   │   f'Unable to generate pydantic-core schema for {obj!r}. '                      │
│    407 │   │   │   'Set `arbitrary_types_allowed=True` in the model_config to ignore this error  │
│    408 │   │   │   ' or implement `__get_pydantic_core_schema__` on your type to fully support   │
╰──────────────────────────────────────────────────────────────────────────────────────────────────╯
PydanticSchemaGenerationError: Unable to generate pydantic-core schema for <class 'sklearn.neighbors._unsupervised.NearestNeighbors'>. Set `arbitrary_types_allowed=True` in the model_config to ignore this error or 
implement `__get_pydantic_core_schema__` on your type to fully support it.

If you got this error by calling handler(<some type>) within `__get_pydantic_core_schema__` then you likely need to call `handler.generate_schema(<some type>)` since we do not call `__get_pydantic_core_schema__` on 
`<some type>` otherwise to avoid infinite recursion.

For further information visit https://errors.pydantic.dev/2.7/u/schema-for-unknown-type

def two(a: Optional[int] = None, nn: Optional[NearestNeighbors] = None):

While primitive types allowed for optional typing, non-serializable types like NearestNeighbors lead to pydantic errors, as the utility functions were only checking serializable types (as the assumption probably was that at this point we are handling only parameters, not artifacts).

Pre-requisites

Please ensure you have done the following:

  • I have read the CONTRIBUTING.md document.
  • If my change requires a change to docs, I have updated the documentation accordingly.
  • I have added tests to cover my changes.
  • I have based my new branch on develop and the open PR is targeting develop. If your branch wasn't based on develop read Contribution guide on rebasing branch to develop.
  • If my changes require changes to the dashboard, these changes are communicated/requested.

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)
  • Other (add details above)

Copy link
Contributor

coderabbitai bot commented Aug 21, 2024

Important

Review skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions github-actions bot added internal To filter out internal PRs and issues bug Something isn't working labels Aug 21, 2024
src/zenml/steps/entrypoint_function_utils.py Outdated Show resolved Hide resolved
src/zenml/steps/entrypoint_function_utils.py Outdated Show resolved Hide resolved
src/zenml/steps/entrypoint_function_utils.py Outdated Show resolved Hide resolved
Copy link
Contributor

@schustmi schustmi left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, this really screams for a test case

@AlexejPenner
Copy link
Contributor Author

Also, this really screams for a test case

already had some, are any obvious ones missing?

value=(annotation, ...),
)
validation_model_class(value=value)
except Exception:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should this be

try:
  ...
except ValidationError:
  raise
except Exception:
  ...

instead? In case pydantic fails with a regular validation error, we actually want to raise that because it means the types don't match right?

validation_model_class(value=value)
except Exception:
# If Pydantic can't handle it, fall back to isinstance
if not isinstance(value, annotation):
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also this might fail with the raw annotation:

isinstance(int, Union[int, str])

# TypeError: Subscripted generics cannot be used with class and instance checks

Copy link
Contributor

@schustmi schustmi left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually I have a more general question regarding this PR:

This is not a json-serializable object, which means by our definition it can never be a parameter. This means this whole PR is related to a step input, which is of a non-json serializable type, for which there is a None default value and no artifact is being passed to it. Is that correct?

If yes, there might be other simpler solutions to prevent this case from even getting to this parameter validation method.

@schustmi
Copy link
Contributor

schustmi commented Aug 27, 2024

I'm still not entirely sure how to handle this. On the one hand, it would be nice to have your code work as is. On the other hand, if someone now we're to switch the default value to something Non-Null, we would fail and say a parameter has to be JSON-serializable, which also seems weird.

In case we want this though, I think we could achieve this by allowing arbitrary types in case the value is None:

def _validate_parameter_input_value(
  self, parameter: inspect.Parameter, value: Any
) -> None:
  arbitrary_types_allowed = value is None
  config_dict = ConfigDict(arbitrary_types_allowed=arbitrary_types_allowed)
  ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working internal To filter out internal PRs and issues run-slow-ci
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants